package com.soft863.tc.common.util;


import com.soft863.tc.common.constant.ValueConstant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionUtil {
    private static final ThreadLocal<Connection> connHolder = new ThreadLocal<>();
    private static final ThreadLocal<Jedis> jedisHolder = new ThreadLocal<>();

    public static synchronized Connection getMySQLConnection() {
        Connection connection = connHolder.get();
        if (connection == null) {
            try {
                connection = DriverManager.getConnection(
                        ValueConstant.MYSQL_URL,
                        ValueConstant.USER,
                        ValueConstant.PWD);
                connHolder.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static synchronized Jedis getJedis() {
        Jedis jedis = jedisHolder.get();
        if (jedis == null) {
            jedis = new Jedis(ValueConstant.REDIS_URL, ValueConstant.REDIS_PORT);
            jedisHolder.set(jedis);
        }
        return jedis;
    }

    public static synchronized void closeMySQL() {
        Connection connection = getMySQLConnection();
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connHolder.remove();
        }
    }

    public static synchronized void closeJedis() {
        Jedis jedis = jedisHolder.get();
        if (jedis != null) {
            jedis.close();
            jedisHolder.remove();
        }
    }
}
